<?php
$errors = array();
if ($_POST) {
	// run the validation script
	require_once('library.php');
	try {
		
		if($_POST['addLabel']){
		// check that label name is 1-50 alphanumeric and not already taken in DB
		$val = new Zend_Validate();
		$length = new Zend_Validate_StringLength(1,50);
		$val->addValidator($length);
		if (!$val->isValid($_POST['labelName'])){
			$errors['labelNameInvalid'] = '*** Use 1-50 letters or numbers only -> ';
			}else{
				$sql = $dbRead->quoteInto('SELECT labelName from labels WHERE labelName = ?',$_POST['labelName']);
				$result = $dbRead->fetchAll($sql);
				if ($result){
					$errors['labelNameDuplicate'] = '*** '.$_POST['labelName'] . ' is already in use -> ';
				}
			}
//check if any labels are to be deleted			
		$val = new Zend_Validate();
		$length = new Zend_Validate_StringLength(1,100);
		$val->addValidator($length);
		if (!$val->isValid($_POST['labelDescription'])){
			$errors['labelDescriptionInvalid'] = '*** Use 1-100 letters or numbers only -> ';
			}
			
			
					
		if(!$errors){
			$data = array('labelName' => $_POST['labelName'],
			
			'labelDescription' => $_POST['labelDescription'],
			              
			'accountId' => $_SESSION['accountId']);
			$dbWrite->insert('labels', $data);
			header('Location: ManageLabels.php');			  
		}
	  }
	  

	if($_POST['deleteLabel']){
		    $sql = 'SELECT labelId FROM `labels` WHERE accountId = ?';
  $result = $dbRead->fetchAll($sql,$_SESSION['accountId']);
  
	  	$labelsSelected = $_POST['labels'];
		  
	  	if(isset($labelsSelected))
  		{
    		$numberLabels = count($labelsSelected);
			if ($numberLabels > 0){
    			for($i=0; $i < $numberLabels; $i++)
   	  			{
	     			$dbWrite->delete('labels','labelId='.$labelsSelected[$i]);
	     		
    			}
			}
  		}
		header('Location: ManageLabels.php');
	}
	
	} catch (Exception $e){
		echo $e->getMessage();
	}
}